//
//  JYInputEmoticomParser.m
//  TestNIMSDK
//
//  Created by jianyong.wang on 2017/6/2.
//  Copyright © 2017年 jianyong.wang. All rights reserved.
//

#import "JYInputEmoticomParser.h"
#import "JYEmojiManager.h"
@implementation JYInputTextToken
@end
@interface JYInputEmoticomParser()
@property(nonatomic,strong)NSCache * tokens;//仅作为缓存使用
@end
@implementation JYInputEmoticomParser
+(instancetype)currentParaser
{
    static JYInputEmoticomParser * paraseInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        paraseInstance = [[JYInputEmoticomParser alloc]init];
    });
    return paraseInstance;
}
-(instancetype)init
{
    if (self = [super init]) {
        _tokens = [[NSCache alloc]init];
    }
    return self;
}

//获取缓存
-(NSArray *)tokens:(NSString *)text
{
    NSArray * tokens = nil;
    if ([text length]) {
        tokens = [_tokens objectForKey:text];
        if (tokens==nil) {
            tokens = [self parseToken:text];
            [_tokens setObject:tokens forKey:text];
        }
    }
    return tokens;
}
-(NSArray *)parseToken:(NSString *)text
{
    NSMutableArray * tokens = [NSMutableArray array];
    
    NSRegularExpression * exp = [NSRegularExpression regularExpressionWithPattern:@"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    __block NSInteger index = 0;
    [exp enumerateMatchesInString:text options:0 range:NSMakeRange(0, text.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
        NSString *rangeText = [text substringWithRange:result.range];
        if([[JYEmojiManager sharedManager] emoticonByTag:rangeText])
        {
            if (result.range.location > index) {
                //如果得到的第一个 [大笑] 的位置>0，那么说明前面的为正常文本，先将正常文本添加至tokens，添加完后再添加 [大笑],如此循环
                NSString * rawText = [text substringWithRange:NSMakeRange(index, result.range.location - index)];
                JYInputTextToken * token  = [[JYInputTextToken alloc]init];
                token.type = JYInputTokenTypeText;
                token.text = rawText;
                [tokens addObject:token];
            }
            JYInputTextToken * token = [[JYInputTextToken alloc]init];
            token.type = JYInputTokenTypeEmoticon;
            token.text = rangeText;
            [tokens addObject:token];
            
            index = result.range.location + result.range.length;
        }
    }];
    //最后如果index小于文本总长度，说明，最后还有一小段正常文本
    if (index < text.length) {
        NSString * rawText = [text substringWithRange:NSMakeRange(index, text.length - index)];
        JYInputTextToken * token = [[JYInputTextToken alloc]init];
        token.type = JYInputTokenTypeText;
        token.text = rawText;
        [tokens addObject:token];
    }
    return tokens;
}
@end
